/**
 * Project Name:alqsoft-ms
 * File Name:BaseInfoProxyFactory.java
 * Package Name:com.alqsoft.interceptor
 * Date:2016年10月27日下午4:07:16
 * Copyright (c) 2016, chenzhou1025@126.com All Rights Reserved.
 *
*/

package com.alqsoft.interceptor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

/**
 * ClassName:BaseInfoProxyFactory <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason:	 TODO ADD REASON. <br/>
 * Date:     2016年10月27日 下午4:07:16 <br/>
 * @author   张灿
 * @version  提供代理工厂方法
 * @since    JDK 1.8
 * @see 	 
 */

public class BaseInfoProxyFactory {
	/**
	 * 内部提供代理类对象工具类
	 * @param c
	 * @param cs
	 * @param ih
	 * @return
	 */
	private static Object getProxy(ClassLoader c,Class<?>[] cs,InvocationHandler ih){
		Object o = Proxy.newProxyInstance(c, cs,ih);
		return o;
	}
	/**
	 * 提供代理类
	 * @param baseInfoHandlers 
	 * @return
	 */
	public static BaseInfoInterface getBaseInfoInterface(BaseInfoHandler[] baseInfoHandlers){
		BaseInfoInterface baseInfo = new BaseInfoImpl();
		for (int i = 0; i < baseInfoHandlers.length; i++) {
			if(baseInfoHandlers[i]==null){
				break;
			}
			baseInfoHandlers[i].setTarget(baseInfo);
			if(i!=0){
				baseInfoHandlers[i-1].setHandler(baseInfoHandlers[i]);
			}
		}
		Object o = getProxy(baseInfo.getClass().getClassLoader(), new Class[]{BaseInfoInterface.class}, baseInfoHandlers[0]);
		return ((BaseInfoInterface)o);
	}
	/**
	 * 测试拦截器；
	 * @param args
	 */
	public static void main(String[] args){
		BaseInfoInterface baseInfo = new BaseInfoImpl();
		BaseInfoHandler handler1 = new BaseInfoHandler2("h1");
		BaseInfoHandler handler2 = new BaseInfoHandler2("h2");
		handler1.setTarget(baseInfo);
		handler2.setTarget(baseInfo);
		handler1.setHandler(handler2);
		Object o = getProxy(baseInfo.getClass().getClassLoader(), new Class[]{BaseInfoInterface.class}, handler1);
		((BaseInfoInterface)o).doFilter("");
	}
}
